var MaterialLayout = function () {
  var MaterialLayoutItem = function () {
    var template = /* html */ `
      <div class="material-layout-item">
        <div>
          <el-form inline>
            <el-form-item label="序号:">
              <span>{{material.lineNo}}</span>
            </el-form-item>
            <el-form-item label="色号:">
              <span>{{material.materialColor}}</span>
            </el-form-item>
            <el-form-item label="色号描述:">
              <span>{{material.materialColorDescription}}</span>
            </el-form-item>
            <el-form-item label="开料方式:">
              <span>{{material.materialKlfs}}</span>
            </el-form-item>
            <el-form-item label="物料规格:">
              <span>{{material.materialModel}}</span>
            </el-form-item>
            <el-form-item label="每条料可开数:">
              <span>{{material.materialMtlktTotal}}</span>
            </el-form-item>
          </el-form>
        </div>
        <div v-if="drawMaterial" class="material-layout-canvas">
          <canvas ref="layout"></canvas>
        </div>
      </div>
    `;

    return {
      props: {
        material: {
          type: Object,
          required: true
        },
        bomForm: {
          type: Object,
          required: true
        },
        paperSize: {
          type: Object,
          required: true
        },
        ratio: {
          type: Number,
          required: true
        }
      },

      data: function () {
        return {
          drawMaterial: null
        };
      },

      created: function () {
        this.setDrawMaterial();
      },

      mounted: function () {
        this.drawLayout();
      },

      methods: {
        setDrawMaterial: function () {
          var material = this.material;
          var width = material.width;
          var ratio = this.ratio;
          width = ModuleUtil.getPixelValue(width * ratio, 'ceil');

          var height = material.height;
          height = ModuleUtil.getPixelValue(height * ratio, 'ceil');

          var beatEdge = material.beatEdge;
          beatEdge = ModuleUtil.getPixelValue(beatEdge * ratio, 'ceil');

          var bomForm = this.bomForm;
          var materialCutData = bomForm.materialCutData;
          var cutGap = materialCutData.cutGap;
          var khhc = materialCutData.khhc;
          khhc = ModuleUtil.getPixelValue((khhc + cutGap) * ratio, 'floor');
          var khhk = materialCutData.khhk;
          khhk = ModuleUtil.getPixelValue((khhk + cutGap) * ratio, 'floor');
          var ztcd = materialCutData.ztcd;
          ztcd = ModuleUtil.getPixelValue(ztcd * ratio, 'floor');
          var ztkd = materialCutData.ztkd;
          ztkd = ModuleUtil.getPixelValue((ztkd + cutGap / 2) * ratio, 'floor');

          this.drawMaterial = {
            width: width,
            height: height,
            beatEdge: beatEdge,
            khhc: khhc,
            khhk: khhk,
            ztcd: ztcd,
            ztkd: ztkd
          };
        },

        drawLayout: function () {
          var drawMaterial = this.drawMaterial;
          var canvas = this.$refs['layout'];
          var width = drawMaterial.width;
          var height = drawMaterial.height;
          canvas.width = width;
          canvas.height = height;

          var ctx = canvas.getContext('2d');
          ctx.clearRect(0, 0, canvas.width, canvas.height);
          ctx.strokeStyle = '#000000';
          ctx.lineWidth = "1";
          var materialCut = this.material.materialCut;
          var materialKlfs = this.material.materialKlfs;
          var startX = 0,
            startY = 0;
          if (width > height) {
            startY = drawMaterial.beatEdge;
          } else {
            startX = drawMaterial.beatEdge;
          }
          ctx.beginPath();
          if (materialKlfs === '横开') {
            this.drawHorizontalMaterial(ctx, materialCut, startX, startY);
          } else if (materialKlfs === '竖开') {
            this.drawVerticalMaterial(ctx, materialCut, startX, startY);
          } else {
            this.drawBonthMaterial(ctx, materialCut, startX, startY);
          }
          ctx.stroke();
        },

        drawHorizontalMaterial: function (ctx, materialCut, startX, startY) {
          var horizontalCol = materialCut.horizontalCol;
          var horizontalRow = materialCut.horizontalRow;
          if (horizontalCol === 0 || horizontalRow === 0) {
            return null;
          }

          var drawMaterial = this.drawMaterial;
          var rangeX = _.round(drawMaterial.khhc - drawMaterial.ztcd, 0) - 1;
          var rangeY = drawMaterial.khhk - 1;
          var x = startX;
          for (var i = 0; i < horizontalRow; i++) {
            startX = x;
            for (var j = 0; j < horizontalCol; j++) {
              var num = i + j;
              if (num % 2 === 0) {
                this.drawMaterialItem(ctx, startX, startY, i, j, 1);
              } else {
                this.drawMaterialItem(ctx, startX, startY, i, j, 2);
              }
              startX += rangeX;
            }
            startY += rangeY;
          }
          return [startX, startY];
        },

        drawVerticalMaterial: function (ctx, materialCut, startX, startY) {
          var verticalCol = materialCut.verticalCol;
          var verticalRow = materialCut.verticalRow;
          if (verticalCol === 0 || verticalRow === 0) {
            return null;
          }

          var drawMaterial = this.drawMaterial;
          var rangeX = drawMaterial.khhk - 1;
          var rangeY = _.round(drawMaterial.khhc - drawMaterial.ztcd, 0) - 1;
          var x = startX;
          for (var i = 0; i < verticalRow; i++) {
            startX = x;
            for (var j = 0; j < verticalCol; j++) {
              var num = i + j;
              if (num % 2 === 0) {
                this.drawMaterialItem(ctx, startX, startY, i, j, 3);
              } else {
                this.drawMaterialItem(ctx, startX, startY, i, j, 4);
              }
              startX += rangeX;
            }
            startY += rangeY;
          }
          return [startX, startY];
        },

        drawBonthMaterial: function (ctx, materialCut, startX, startY) {
          var type = materialCut.type;
          var drawMaterial = this.drawMaterial;
          var x = startX,
            y = startY;
          if (type === 1) {
            var pos = this.drawHorizontalMaterial(ctx, materialCut, startX, startY);
            if (pos !== null) {
              startX = pos[0] + drawMaterial.ztcd;
              startY = y;
            }
            this.drawVerticalMaterial(ctx, materialCut, startX, startY);
          } else if (type === 2) {
            var pos = this.drawVerticalMaterial(ctx, materialCut, startX, startY);
            if (pos !== null) {
              startX = x;
              startY = pos[1] + drawMaterial.ztcd;
            }
            this.drawHorizontalMaterial(ctx, materialCut, startX, startY);
          }
        },

        drawMaterialItem: function (ctx, startX, startY, rowIndex, colIndex, type) {
          var drawMaterial = this.drawMaterial;
          var khhc = drawMaterial.khhc;
          var khhk = drawMaterial.khhk;

          var ztcd = drawMaterial.ztcd;
          if (ztcd === 0) {
            if ([1,2].indexOf(type) !== -1) {
              ctx.moveTo(startX + 0.5, startY + 0.5);
              if (colIndex === 0) {
                ctx.lineTo(startX + 0.5, startY + drawMaterial.khhk - 0.5);
              } else {
                ctx.moveTo(startX + 0.5, startY + drawMaterial.khhk - 0.5);
              }
              ctx.lineTo(startX + drawMaterial.khhc - 0.5, startY + drawMaterial.khhk - 0.5);
              ctx.lineTo(startX + drawMaterial.khhc - 0.5, startY + 0.5);
              if (rowIndex === 0) {
                ctx.lineTo(startX + 0.5, startY + 0.5);
              }
            } else {
              ctx.moveTo(startX + 0.5, startY + 0.5);
              if (colIndex === 0) {
                ctx.lineTo(startX + 0.5, startY + drawMaterial.khhc - 0.5);
              } else {
                ctx.moveTo(startX + 0.5, startY + drawMaterial.khhc - 0.5);
              }
              ctx.lineTo(startX + drawMaterial.khhk - 0.5, startY + drawMaterial.khhc - 0.5);
              ctx.lineTo(startX + drawMaterial.khhk - 0.5, startY + 0.5);
              if (rowIndex === 0) {
                ctx.lineTo(startX + 0.5, startY + 0.5);
              }
            }
            return;
          }

          var ztkd = drawMaterial.ztkd;
          var khhk = drawMaterial.khhk;
          var khhc = drawMaterial.khhc;
          if (type === 1) {
            ctx.moveTo(startX + ztcd - 0.5, startY + 0.5);
            if (colIndex === 0) {
              ctx.lineTo(startX + ztcd - 0.5, startY + ztkd - 0.5);
              ctx.lineTo(startX + 0.5, startY + khhk - ztkd - 0.5);
              ctx.lineTo(startX + 0.5, startY + khhk - 0.5);
            } else {
              ctx.moveTo(startX + 0.5, startY + khhk - 0.5);
            }
            ctx.lineTo(startX + khhc - 0.5, startY + khhk - 0.5);
            ctx.lineTo(startX + khhc - 0.5, startY + khhk - ztkd - 0.5);
            ctx.lineTo(startX + khhc - ztcd - 0.5, startY + ztkd - 0.5);
            ctx.lineTo(startX + khhc - ztcd - 0.5, startY + 0.5);
            if (rowIndex === 0) {
              ctx.lineTo(startX + ztcd - 0.5, startY + 0.5);
            }
          } else if (type === 2) {
            ctx.moveTo(startX + 0.5, startY + 0.5);
            if (colIndex === 0) {
              ctx.lineTo(startX + 0.5, startY + ztkd - 0.5);
              ctx.lineTo(startX + ztcd - 0.5, startY + khhk - ztkd - 0.5);
              ctx.lineTo(startX + ztcd - 0.5, startY + khhk - 0.5);
            } else {
              ctx.moveTo(startX + ztcd - 0.5, startY + khhk - 0.5);
            }
            ctx.lineTo(startX + khhc - ztcd - 0.5, startY + khhk - 0.5);
            ctx.lineTo(startX + khhc - ztcd - 0.5, startY + khhk - ztkd - 0.5);
            ctx.lineTo(startX + khhc - 0.5, startY + ztkd - 0.5);
            ctx.lineTo(startX + khhc - 0.5, startY + 0.5);
            if (rowIndex === 0) {
              ctx.lineTo(startX + 0.5, startY + 0.5);
            }
          } else if (type === 3) {
            ctx.moveTo(startX + 0.5, startY + ztcd - 0.5);
            if (colIndex === 0) {
              ctx.lineTo(startX + 0.5, startY + khhc - ztcd - 0.5);
            } else {
              ctx.moveTo(startX + 0.5, startY + khhc - ztcd - 0.5);
            }
            ctx.lineTo(startX + ztkd - 0.5, startY + khhc - ztcd - 0.5);
            ctx.lineTo(startX + khhk - ztkd - 0.5, startY + khhc - 0.5);
            ctx.lineTo(startX + khhk - 0.5, startY + khhc - 0.5);
            ctx.lineTo(startX + khhk - 0.5, startY + 0.5);
            if (rowIndex === 0) {
              ctx.lineTo(startX + khhk - ztkd - 0.5, startY + 0.5);
              ctx.lineTo(startX + ztkd - 0.5, startY + ztcd + 0.5);
              ctx.lineTo(startX + 0.5, startY + ztcd - 0.5);
            }
          } else if (type === 4) {
            ctx.moveTo(startX + 0.5, startY + 0.5);
            if (colIndex === 0) {
              ctx.lineTo(startX + 0.5, startY + khhc - 0.5);
            } else {
              ctx.moveTo(startX + 0.5, startY + khhc - 0.5);
            }
            ctx.lineTo(startX + ztkd - 0.5, startY + khhc - 0.5);
            ctx.lineTo(startX + khhk - ztkd - 0.5, startY + khhc - ztcd - 0.5);
            ctx.lineTo(startX + khhk - 0.5, startY + khhc - ztcd - 0.5);
            ctx.lineTo(startX + khhk - 0.5, startY + ztcd - 0.5);

            if (rowIndex === 0) {
              ctx.lineTo(startX + khhk - ztkd - 0.5, startY + ztcd - 0.5);
              ctx.lineTo(startX + ztkd - 0.5, startY + 0.5);
              ctx.lineTo(startX + 0.5, startY + 0.5);
            }
          }
        }
      },

      template: template
    };
  }();

  var template = /* html */ `
    <div class="material-layout" v-loading.fullscreen.lock="loading">
      <template v-if="isShow">
        <template v-if="errorMsg===''">
        <div class="material-layout-btns">
          <el-form inline size="small">
            <el-form-item label="纸张大小">
              <el-select v-model="paperSize" value-key="id" style="width:180px" @change="paperSizeChange">
                <el-option v-for="item in paperSizeList" :key="item.id" :value="item" :label="item.label"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="printLayout">打印</el-button>
            </el-form-item>
          </el-form>
        </div>
        <div :key="layoutKey" class="material-layout-content print-area">
          <div style="text-align:center">工厂型号：{{bomForm.factoryNo}}</div>
          <el-form v-if="materialCutData!==null" inline size="small">
            <el-form-item label="开料长度">
              <span>{{materialCutData.khhc}}</span>
            </el-form-item>
            <el-form-item label="开料宽度">
              <span>{{materialCutData.khhk}}</span>
            </el-form-item>
            <el-form-item label="桩头长度">
              <span>{{materialCutData.ztcd}}</span>
            </el-form-item>
            <el-form-item label="桩头宽度">
              <span>{{materialCutData.ztkd}}</span>
            </el-form-item>
          </el-form>
          <material-layout-item v-for="(material,index) in materialList" :key="'material_'+index" :material="material" :bom-form="bomForm"
            :paper-size="paperSize" :ratio="ratio">
          </material-layout-item>
        </div>
        </template>
        <div v-else class="no-data">
          <div>{{errorMsg}}</div>
        </div>
      </template>
    </div>
  `;

  return {
    props: {
      bomForm: {
        type: Object,
        required: true
      }
    },

    computed: {
      layoutKey: function () {
        var paperSize = this.paperSize;
        if (paperSize === '') {
          return 'noneKey';
        }
        this.setRatio();
        return paperSize.id;
      }
    },

    data: function () {
      return {
        loading: false,
        isShow: false,
        materialList: [],
        materialCutData: null,
        errorMsg: '',
        paperSize: '',
        ratio: 1,
        maxWidth: null,
        paperSizeList: [{
          id: 'a3-vertical',
          label: 'A3(纵向)',
          width: 270,
          height: 400
        }, {
          id: 'a3-horizontal',
          label: 'A3(横向)',
          width: 400,
          height: 270
        }, {
          id: 'a4-vertical',
          label: 'A4(纵向)',
          width: 190,
          height: 270
        }, {
          id: 'a4-horizontal',
          label: 'A4(横向)',
          width: 270,
          height: 190
        }]
      };
    },

    created: function () {
      var paperSizeList = this.paperSizeList;
      var id = localStorage.getItem('materialLayoutPaperSize');
      if (SysUtil.isEmpty(id)) {
        this.paperSize = paperSizeList[3];
      } else {
        var paperSize = _.find(paperSizeList, {
          id: id
        });
        this.paperSize = paperSize;
      }

      this.loading = true;
      var self = this;
      this.setMaterialList().then(function (materialList) {
        var maxWidth = 0;
        materialList = _.map(materialList, function (material) {
          var materialObj = material.materialObj;
          var arr = ModuleUtil.getSize(materialObj.materialModel);
          var beatEdge = material.beatEdge;
          if (beatEdge === undefined) {
            beatEdge = 0;
          }
          var width = arr[0];
          if (maxWidth < width) {
            maxWidth = width;
          }
          return {
            lineNo: material.lineNo,
            materialKlfs: material.materialKlfs,
            materialColor: materialObj.materialColor,
            materialColorDescription: materialObj.materialColorDescription,
            materialModel: materialObj.materialModel,
            width: width,
            height: arr[1],
            beatEdge: beatEdge,
            materialCut: materialObj.materialCut,
            materialMtlktTotal: material.materialMtlktTotal
          };
        });

        self.maxWidth = maxWidth;
        self.setRatio();

        self.materialList = materialList;
        self.errorMsg = '';
        self.isShow = true;
        self.loading = false;
      }).catch(function (errorMsg) {
        self.errorMsg = errorMsg;
        self.isShow = true;
        self.loading = false;
      });
    },

    methods: {
      setMaterialList: function () {
        var bomForm = this.bomForm;
        var materialCutData = bomForm.materialCutData;
        var code = ModuleUtil.checkValid(materialCutData);
        if (code !== '') {
          return Promise.reject('开圈数据未设定');
        }
        this.materialCutData = materialCutData;

        var materialColorBomList = bomForm.materialColorBomList;
        var materialKlfsObj = {
          "横开": 1,
          "竖开": 2,
          "双向": 3
        };
        var materialList = [];
        var materials = [],
          materialPostData = [];
        for (var i = 0; i < materialColorBomList.length; i++) {
          var material = materialColorBomList[i];
          var materialType = _.get(material, 'materialType.materialType', '');
          if (materialType !== '板材圈') {
            continue;
          }

          var materialKlfs = material.materialKlfs;
          if (materialKlfs === '') {
            continue;
          }

          var materialObj = material.materialObj;
          if (materialObj === null) {
            continue;
          }
          var arr = ModuleUtil.getSize(materialObj.materialModel);
          if (arr === null) {
            continue;
          }
          materialList.push(material);

          if (materialObj.materialCut === undefined) {
            materials.push(material);

            var beatEdge = material.beatEdge;
            if (beatEdge === undefined) {
              beatEdge = 0;
            }
            materialPostData.push({
              ylc52: arr[0],
              ylk53: arr[1],
              sbl54: beatEdge,
              kllx700: materialKlfsObj[materialKlfs],
              xbl55: 0
            });
          }
        }

        if (materialList.length === 0) {
          return Promise.reject('颜色物料BOM中无物料类型为板材圈，物料规格符合格式的物料');
        }

        if (materials.length === 0) {
          return Promise.resolve(materialList);
        }

        materialPostData = _.map(materialPostData, function (obj) {
          obj.khhc58 = materialCutData.khhc;
          obj.khhk59 = materialCutData.khhk;
          obj.ztcd61 = materialCutData.ztcd;
          obj.ztkd60 = materialCutData.ztkd;
          obj.qf717 = materialCutData.cutGap;
          return obj;
        });

        return ModuleUtil.calRingMaterialListCut(materialPostData).then(function (dataList) {
          for (var i = 0; i < dataList.length; i++) {
            var obj = dataList[i];
            var material = materials[i];
            material.materialObj.materialCut = obj;
          }
          return materialList;
        }).catch(function () {
          throw new Error('计算开圈排版失败');
        });
      },

      setRatio: function () {
        var maxWidth = this.maxWidth;
        var paperSize = this.paperSize;
        var width = paperSize.width - 5;
        var ratio = 1;
        if (maxWidth > width) {
          ratio = width / maxWidth;
        }
        this.ratio = ratio;
      },

      paperSizeChange: function () {
        var paperSize = this.paperSize;
        var id = paperSize.id;
        localStorage.setItem('materialLayoutPaperSize', id);
      },

      printLayout: function () {
        window.print();
      }
    },

    components: {
      MaterialLayoutItem: MaterialLayoutItem
    },

    template: template
  };
}();
